<!--
 * @Description: 
 * @Author: your name
 * @version: 
 * @Date: 2024-05-08 16:34:13
 * @LastEditors: your name
 * @LastEditTime: 2024-09-10 09:25:51
-->
<template>
  <div id="cesium-viewer">
    <ToolBar />
    <HeavyProtectionActivity />
    <DevelopmentHistory />
    <slot />
    <SubwayManager />
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'
import { onMounted, markRaw, ref, watch, onUnmounted } from 'vue'
import app from '../main'
import {
  initViewer,
  setScene,
  loadTilesets,
  handleDefaultModelEffect,
  flyToDefaultView,
} from '@/cesiumTools/sceneManager'
import { useLineData } from '@/store'
import { getWeather } from '@/api/line.js'
import { SubwayLineDrawer } from '@/cesiumTools/lineDrawer'
import SubwayManager from '@/components/SubwayManager.vue'
import ToolBar from '@/components/ToolBar.vue'
import HeavyProtectionActivity from '@/components/HeavyProtectionActivity.vue'
import DevelopmentHistory from '@/components/DevelopmentHistory.vue'
import {
  renderStation,
  removeStation,
  getStations,
} from '@/cesiumTools/effectController'

const lineDataStore = useLineData()
const lineDrawer = ref(null)

// 一定要在任何 Cesium API 调用前设置 token
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzODQ2OTk2My1iNjRmLTRiZjgtOGVjNS0yMWMyZTU2MWJjOGMiLCJpZCI6MzA2MDkxLCJpYXQiOjE3NDg0MzAxMDl9.ZJ3EnnkmtpeXdPfKzSCedWnG2Fbex41RLMlAB6WD9s8'

onMounted(async () => {
  const viewer = initViewer('cesium-viewer')
  const data = await getWeather()
  console.log(data)

  setScene(viewer)
  flyToDefaultView(viewer)

  // 创建线路绘制工具实例
  lineDrawer.value = new SubwayLineDrawer(viewer)

  const modelUrls = [
    {
      url: 'http://localhost:8888/wuhan/tileset.json',
      options: {},
    },
  ]
  lineDataStore.setViewer(markRaw(viewer))
  // 加载多个3dtiles
  await loadTilesets(viewer, modelUrls, (tilesets) => {
    handleDefaultModelEffect(tilesets[0])
    lineDataStore.setTileset(markRaw(tilesets[0]))
  })

  // 示例：渲染一个站点（可根据实际数据循环渲染）
  renderStation(viewer, {
    position: { lng: 114.32, lat: 30.71 },
    color: Cesium.Color.fromCssColorString('#4A90E2'),
    name: '站点A',
  })
})

// 监听线路数据变化
watch(
  () => lineDataStore.lines,
  (lines) => {
    if (lineDrawer.value && lines) {
      // 先清除现有的线路
      lineDrawer.value.clear()
      // 重新绘制所有线路
      lines.forEach((line) => {
        lineDrawer.value.drawLine(line)
      })
    }
  },
  { deep: true }
)

// 监听线路显示状态变化
watch(
  () =>
    lineDataStore.lines.map((line) => ({ name: line.name, show: line.show })),
  (lines) => {
    if (lineDrawer.value) {
      lines.forEach((line) => {
        lineDrawer.value.updateLineVisibility(line.name, line.show)
      })
    }
  },
  { deep: true }
)

// 组件卸载时清理资源
onUnmounted(() => {
  if (lineDrawer.value) {
    lineDrawer.value.destroy()
  }
})
</script>
<style>
#cesium-viewer {
  width: 100%;
  height: 100%;
  pointer-events: all;
}
</style>
